package com.example.demo.common.exception.handler;

import com.example.demo.common.enums.CodeEnum;
import com.example.demo.common.exception.BaseRuntimeException;
import com.example.demo.common.result.R;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常处理
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(BaseRuntimeException.class)
    @ResponseBody
    public R handleCustomException(BaseRuntimeException ex) {
        logger.error("BaseRuntime Exception: {}", ex.getMessage(), ex);
        return R.fail(ex.getCode(), ex.getMessage());
    }


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R handleException(Exception ex) {
        logger.error("Unexpected Exception: {}", ex.getMessage(), ex);
        return R.fail(CodeEnum.NOMOREFAILURE.getCode(), CodeEnum.NOMOREFAILURE.getMsg());
    }
}
